/*
 * <p>Copyright® 2009-2022 东软 IT 实训中心版权所有。</p>
 */

package com.max.back.doctor.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.max.back.doctor.dao.*;
import com.max.back.doctor.service.PatientHistoryService;
import com.max.back.doctor.service.RegistrationService;
import com.max.back.entity.Doctor;
import com.max.back.entity.Patient;
import com.max.back.entity.PatientHistory;
import com.max.back.entity.Registration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 辛凤文 forward.seen@foxmail.com
 * @version 1.0
 * @description <p>
 * <code>PatientHistoryServiceImpl</code>
 *
 * </p>
 * @time 2022/7/19 14:23
 * @see
 */
@Service
public class PatientHistoryServiceImpl extends ServiceImpl<PatientHistoryDao,
        PatientHistory> implements PatientHistoryService {

    @Autowired
    private DoctorDao doctorDao;

    @Autowired
    private PatientDao patientDao;

    @Autowired
    private RegistrationDao registrationDao;

    @Autowired
    private RegistrationService registrationService;

    @Override
    public List<PatientHistory> queryAll() {
        return list();
    }

    @Override
    public String createOneAndReturnID(String registrationId) {
        String doctorId =
                doctorDao.selectIdByRegistrationId(registrationId).getId();
        String patientId = patientDao.selectIdByRegistrationId(registrationId).getId();
        String patientHistoryId = null;
        //如果未接诊说明无病历
        if (CodeNameDao.NOT_OVERCHARGE.equals(registrationService.getRegistrationStatusById(registrationId))) {
            // 新建病历
            patientHistoryId = IdUtil.simpleUUID();
            PatientHistory patientHistory = new PatientHistory();
            patientHistory.setId(patientHistoryId);
            patientHistory.setDoctorId(doctorId);
            patientHistory.setPatientId(patientId);
            patientHistory.setDeleted(false);
            // 未接诊修改为已接诊
            registrationDao.updateStatusById(registrationId,
                    CodeNameDao.ACCEPTS);
            // 返回病历ID
            return save(patientHistory) ? patientHistoryId : null;
        }
        // 接诊中或已接诊状态
        // 根据doctorId、patientId查询病历，按时间降序排序，取第一个
        Map<String, Object> queryConditions = new HashMap<>();
        queryConditions.put("doctor_Id",doctorId);
        queryConditions.put("patient_Id",patientId);
        queryConditions.put("DELETED",0);
        patientHistoryId =
                getOne(new QueryWrapper<PatientHistory>()
                        .allEq(queryConditions)
                        .orderByDesc("GMT_MODIFY"))
                        .getId();
        // 返回病历ID
        return patientHistoryId;
    }
}